package avicit.bdp.dds.api.job;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Enumeration;
import java.util.concurrent.ConcurrentHashMap;

/**
 * websocket流程实例状态服务
 *
 * @author xugb
 * @date 2022/4/6 17:45
 */
@Component
@ServerEndpoint("/api/bdp/dds/websocket/process")
public class WebSocketProcessStausServer {
    private static final Logger logger = LoggerFactory.getLogger(WebSocketProcessStausServer.class);
    private static ConcurrentHashMap<String, Session> sessionPools = new ConcurrentHashMap<>();

    /**
     * 连接建立成功调用
     *
     * @param session 客户端与socket建立的会话
     */
    @OnOpen
    public void onOpen(Session session) {
        String key = session.getId();
        sessionPools.put(key, session);
    }

    /**
     * 关闭连接时调用
     */
    @OnClose
    public void onClose(Session session) {
        String key = session.getId();
        sessionPools.remove(key);
    }

    @OnMessage
    public void onMessage(Session session, String message) {
        if ("ping".equalsIgnoreCase(message)) {
            sendMessage(session, "pong");
            return;
        } else {
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            sendMessage(session, message);
        }
    }

    @OnError
    public void onError(Throwable throwable, Session session) {
        String key = session.getId();
        sessionPools.remove(key);
    }

    /**
     * 发送消息方法
     *
     * @param session 客户端与socket建立的会话
     * @param message 消息
     */
    public void sendMessage(Session session, String message) {
        try {
            if (session != null && session.isOpen()) {
                session.getBasicRemote().sendText(message);
            }
        } catch (IOException e) {
            logger.error(e.getMessage(), e);
        }
    }

    public void sendMessage(String message) throws IOException {
        Enumeration<String> keys = sessionPools.keys();
        while (keys.hasMoreElements()) {
            String key = keys.nextElement();
            Session session = sessionPools.get(key);
            if (session != null && session.isOpen()) {
                sendMessage(session, message);
            } else {
                sessionPools.remove(key);
            }
        }
    }

}
